<template>
 <div ref="amisBox" class="box"/>
</template>

<script setup>
import 'amis/sdk/sdk.js';
import 'amis/lib/themes/default.css';
import "amis/lib/themes/antd.css";
import "amis/lib/themes/cxd.css";
import 'amis/sdk/iconfont.css'
import '@fortawesome/fontawesome-free/css/all.css'
import '@fortawesome/fontawesome-free/css/v4-shims.css';
import axios from 'axios'
import request from '@/utils/request'
import copy from 'copy-to-clipboard'
import * as qs from 'qs'
import { ElMessage } from 'element-plus'
import { alert, confirm, render as renderSchema, toast } from 'amis'
import { createRoot } from 'react-dom/client';

import 'exceljs'
const propsData = defineProps({
  schema: {
    type: Object,
    required: true
  }
}),
amisScoped=$ref(null),//amis实例
amisBox=$ref(null);//dom ref

function initEnv() {
      window.enableAMISDebug = false
      return {
        theme: 'cxd',
        enableAMISDebug: false,
        session: 'global',
        updateLocation: updateRoute(),
        isCurrentUrl: to => {
          const link = this.normalizeLink(to)
          const location = window.location
          let pathname = link
          let search = ''
          const idx = link.indexOf('?')
          if (~idx) {
            pathname = link.substring(0, idx)
            search = link.substring(idx)
          }
          if (search) {
            if (pathname !== location.pathname || !location.search) {
              return false
            }
            const query = qs.parse(search.substring(1))
            const currentQuery = qs.parse(location.search.substring(1))
            return Object.keys(query).every(
              key => query[key] === currentQuery[key]
            )
          } else if (pathname === location.pathname) {
            return true
          }
          return false
        },
        fetcher: ({ url, method, data, config, headers }) => {
          return request({url,method,data,amis:true})
          // config = config || {}
          // config.headers = config.headers || {}
          // config.withCredentials = true

          // if (config.cancelExecutor) {
          //   config.cancelToken = new axios.CancelToken(config.cancelExecutor)
          // }

          // config.headers = headers || {}
          // config.method = method
          // if (method === 'get' && data) {
          //   config.params = data
          // } else if (data && data instanceof FormData) {
          //   // config.headers = config.headers || {};
          //   // config.headers['Content-Type'] = 'multipart/form-data';
          // } else if (
          //   data &&
          //   typeof data !== 'string' &&
          //   !(data instanceof Blob) &&
          //   !(data instanceof ArrayBuffer)
          // ) {
          //   data = JSON.stringify(data)
          //   // config.headers = config.headers || {};
          //   config.headers['Content-Type'] = 'application/json'
          // }

          // data && (config.data = data)

          // const service = axios.create({
          //   // axios中请求配置有baseURL选项，表示请求URL公共部分
          //   baseURL: process.env.VUE_APP_BASE_API,
          //   // 超时
          //   timeout: 10000
          // })
          // return axios(url, config)
        },
        //  responseAdaptor(api, payload, query, request, response) {
        //    console.log(api, payload, query, request, response,'xxxxxxxxxxxxxxxxxx');
        //       return payload;
        // },
        isCancel: e => axios.isCancel(e),
        alert,
        notify: (type, msg) => {
          // toast[type]
          //   ? toast[type](msg, type === 'error' ? '系统错误' : '系统消息')
          //   : console.warn('[Notify]', type, msg)
          if(type!='error'){
			ElMessage({
			  	showClose: true,
			  	message: msg,
			  	type: type,
				duration:2000
			})
          }
          // console.log('[notify]', type, msg, toast)
        },
        confirm,
        copy: (contents, options = {}) => {
          const ret = copy(contents, options)
          ret &&
            (!options || options.shutup !== true) &&
			ElMessage({
				showClose: true,
				message: '内容已拷贝到剪切板',
				type: 'info',
				duration:2000
			  })
          return ret
        },
        tracker: (eventTrack, props)=>{
          try{
            if(props&&(props.store||props.data)){
              const amisId=getAmisId(props.store?props.store.data:props.data)
              if(amisId&&window.amisTracker&&window.amisTracker[amisId]){
                window.amisTracker[amisId](eventTrack,props)
              }
            }
          }catch(e){}
        }
      }
    }
	function getAmisId(data){
	  let amisId=''
	  if(data.__amisId){
	    amisId=data.__amisId
	  }else if(data.__super){
	    amisId=getAmisId(data.__super)
	  }
	  return amisId
	}
	function updateRoute(location, replace) {
	  // if (location === 'goBack') {
	  //   return this.$router.go(-1)
	  // }
	  // if (replace)
	  //   this.$router[replace ? 'replace' : 'push'](this.normalizeLink(location))
	}

	function normalizeLink(to) {
	  if (/^\/api\//.test(to)) {
	    return to
	  }
	  to = to || ''
	  const location = window.location
	  if (to && to[0] === '#') {
	    to = location.pathname + location.search + to
	  } else if (to && to[0] === '?') {
	    to = location.pathname + to
	  }
	  const idx = to.indexOf('?')
	  const idx2 = to.indexOf('#')
	  let pathname = ~idx
	    ? to.substring(0, idx)
	    : ~idx2
	    ? to.substring(0, idx2)
	    : to
	  const search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : ''
	  const hash = ~idx2 ? to.substring(idx2) : ''
	  if (!pathname) {
	    pathname = location.pathname
	  } else if (pathname[0] != '/' && !/^https?:\/\//.test(pathname)) {
	    const relativeBase = location.pathname
	    const paths = relativeBase.split('/')
	    paths.pop()
	    let m
	    while ((m = /^\.\.?\//.exec(pathname))) {
	      if (m[0] === '../') {
	        paths.pop()
	      }
	      pathname = pathname.substring(m[0].length)
	    }
	    pathname = paths.concat(pathname).join('/')
	  }
	  return pathname + search + hash
	}
	//获取amis数据
	function getValues(name){
	  let promise = new Promise((resolve,reject)=>{
	    try{
	      resolve(amisScoped.getComponentByName(name).getValues())
	    }catch(e){
	      resolve(null)
	    }
	  })
	  return promise
	}

	function handleAction(e, action) {
      // console.log(e,action)
    }
	
	onMounted(() => {
		const schema=JSON.parse(JSON.stringify(propsData.schema))
		if(!schema.cssVars){
		  schema.cssVars={}
		}
		schema.cssVars["--Table-fontSize"]='14px'
		// schema.cssVars["--TableCell-paddingY"]='10px'
		schema.cssVars["--Table-searchableForm-backgroundColor"]='#fff'
		schema.cssVars["--Tree-max-height"]="2000px"
		schema.cssVars["--Page-aside-width"]="240px"
		// schema.cssVars["--inputFile-list-marginTop"]="4px"
		
		createRoot(amisBox).render(
			renderSchema(
			 schema,
			  {
				  onAction:(e, action)=>{handleAction(e, action)},
				  scopeRef: (ref) => (amisScoped=ref)
			  },
			  initEnv()
			)
		)
		//该形式curd组件导出报错
		// amisScoped=amisRequire('amis/embed').embed(
		//   amisBox, 
		//   schema,
		//   {},
		//   initEnv()
	 //  )
	})
	
	defineExpose({
		getValues
	});

</script>
<style lang="scss" scoped>
</style>
